// pages/init/init.js

var app = getApp();
const DB = wx.cloud.database().collection("user_info");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentPage: 1,         // 0-注册，1-登录
    
    account: "",
    name: "",
    password: "",
    confirmPassword: "",
    type: 1,                // 患者-1，医生-2

    doctorDefaultAvater: "cloud://mycloud-5gaz607w0eddc87f.6d79-mycloud-5gaz607w0eddc87f-1317335949/doctorDefaultAvater.jpg",
    patientDefaultAvater: "cloud://mycloud-5gaz607w0eddc87f.6d79-mycloud-5gaz607w0eddc87f-1317335949/patientDefaultAvater.jpg"
  },

  // 注册登录监听
  OnClick(event) {
    console.log("OnClick", event);
    let code = event.currentTarget.dataset.code;

    this.setData({
      currentPage: code,
      account: "",
      name: "",
      password: "",
      confirmPassword: "",
    });
  },

  // 注册
  Register: function() {
    let account   = this.data.account;
    let password  = this.data.password;
    let confirmPw = this.data.confirmPassword;

    if (password != confirmPw) {
      wx.showToast({
        title: '密码错误',
        icon: 'error'
      });
      return;
    }

    // 查询账号是否已存在
    var flag = false;
    DB.where({
      account: account,
    }).get({
      success(res) {
        if (res.data.length != 0) {
          wx.showToast({
            title: '账号已存在',
            icon: "error",
          })
          flag = true;
        } 
      },
      fail(res) {
        console.log("查询失败", res);
        flag = true;
      }
    });

    if (flag == true) return;

    var userInfo = {
      account:       account,
      avater:        this.data.type == 1 ? this.data.patientDefaultAvater : this.data.doctorDefaultAvater,
      birth:         new Date().getTime(),
      lastLoginTime: new Date().getTime(),
      nickName:      account,
      password:      password,
      phone:         "",
      realName:      this.data.name,
      sex:           "",
      type:          this.data.type,
      myAsk:         [],
      myDoctor:      [],
      myCar:         [],
      myOrder:       []
    };

    console.log("userInfo:", userInfo);

    // 添加到数据库
    var that = this;
    wx.cloud.callFunction({
      name: 'add_user_info',
      data: {
        userInfo: userInfo
      },
      success: res => {
        console.log("add user success", res);

        // 医生表增加记录
        if (userInfo.type == 2) {
          const doctorInfo = {
            _id:        res.result._id,
            advantage:  "有丰富的临床经验",
            desc:       "教授",
            department: 0,
            image:      userInfo.avater,
            level:      0,
            name:       userInfo.realName,
            workTime:   1
          };

          wx.cloud.callFunction({
            name: 'add_doctor',
            data: {
              doctorInfo: doctorInfo
            },
            success: res => {
              console.log("add doctor success", res);
            },
            fail: res => {
              console.log("add doctor fail", res);
            }
          });
        }

        wx.showToast({
          title: '注册成功',
          icon: 'success'
        });

        that.setData({
          currentPage: 1
        });
      },
      fail: res => {
        console.log("add user fail", res);
        wx.showToast({
          title: '注册失败',
          icon: 'error'
        });
      }
    });
  },

  // 登录
  Login: function() {

    var that = this;

    wx.cloud.callFunction({
      name: "get_user_info",
      data: {
        account: that.data.account,
        password: that.data.password
      },
      success: res => {
        console.log("success", res);

        let len = res.result.data.length;
        console.log("len: ", len);

        if (len == 0) {
          wx.showToast({
            title: '账号密码错误',
            icon: "error"
          });
          return;
        } 

        app.setGlobalData(res.result.data[0]);

        wx.switchTab({
          url: '/pages/home/home',
        });
      },
      fail: res => {
        console.log("fail", res);

        wx.showToast({
          title: '登录错误',
          icon: "error"
        });
      }
    })

  },

  // 点击注册登录按钮
  onRegisterOrLogin(event) {
    console.log("onRegisterOrLogin", event);

    console.log("account: ", this.data.account);
    console.log("password: ", this.data.password);

    this.data.currentPage == 1 ? this.Login() : this.Register();
  },

  // 获取账号
  onInputAccount(event) {
    console.log("onInputAccount", event);
    this.setData({
      account: event.detail.value
    });
  },

  // 获取姓名
  onInputName(event) {
    console.log("onInputName", event);
    this.setData({
      name: event.detail.value
    });
  },

  // 获取密码
  onInputPassworcd(event) {
    console.log("onInputPassworcd", event);
    this.setData({
      password: event.detail.value
    });
  },

  // 获取确认密码
  onInputConfirmPassworcd(event) {
    console.log("onInputConfirmPassworcd", event);
    this.setData({
      confirmPassword: event.detail.value
    });
  },

  // 获取注册身份
  onClickRadio(event) {
    console.log("onClickRadio", event);
    const type = event.detail == "患者" ? 1 : 2;

    this.setData({
      type: type
    });
  },

  // 生命周期函数--监听页面初次渲染完成
  onLoad(options) {
    this.setData({
      account: "",
      name: "",
      password: "",
      confirmPassword: "",
      currentPage: 1,
      type: 1
    });
  },

  // 生命周期函数--监听页面初次渲染完成
  onReady() { },

  // 生命周期函数--监听页面显示
  onShow() { },

  // 生命周期函数--监听页面隐藏
  onHide() { },

  // 生命周期函数--监听页面卸载
  onUnload() { },

  // 页面相关事件处理函数--监听用户下拉动作
  onPullDownRefresh() { },

  // 页面上拉触底事件的处理函数
  onReachBottom() { },

  // 用户点击右上角分享
  onShareAppMessage() { }
})
